//
//  JigSawQTRecordView.m
//  JigSawKiosk
//
//  Created by Stulberg on 10-10-17.
//  Copyright 2010 FruitonLabs. All rights reserved.
//

#import "JigSawQTRecordView.h"


@implementation JigSawQTRecordView

@synthesize captureView, recButton, stopButton, mCaptureSession ;

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
		isRecording = NO ;
		[self setupViews] ;
		[self setupRecordSession] ;
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
	[[NSColor whiteColor] setFill];
    NSRectFill(dirtyRect);
}

-(void) setupViews {
	
	// create and display the capture record window
	float mWidth = [self bounds].size.width ;
	float mHeight = (mWidth*9)/16 ;
	
	NSRect rRect = NSMakeRect(0, 0, mWidth, mHeight) ;
	// setup the movie capture view
	captureView = [[QTCaptureView alloc] initWithFrame:rRect] ;
	[captureView setAutoresizingMask:NSViewWidthSizable|NSViewMinXMargin|NSViewMinYMargin];
	//[captureView setBounds:NSMakeRect(240, 0, 100, 100)] ;
	[self addSubview:captureView] ;
}

- (void)toggleRecording:(NSString*) path 
{
	if (!isRecording) {
		//recordingFilePath = [NSString stringWithFormat:@"%@%@.mov", kMovieRecordPath, [NSDate date]];
		[mCaptureMovieFileOutput recordToOutputFileURL:[NSURL fileURLWithPath:path]];
		isRecording = YES ;
	}
    else {
		[mCaptureMovieFileOutput recordToOutputFileURL:nil];
		isRecording = NO ;
	}
}

-(void) startRecording:(NSString*) path {
	if (!isRecording) {
		//NSStringrecordingFilePath = [NSString stringWithFormat:@"%@%@.mov", kMovieRecordPath, filenameToRecordTo];
		[mCaptureMovieFileOutput recordToOutputFileURL:[NSURL fileURLWithPath:path]];
		isRecording = YES ;
	}
}

-(void) stopRecording {
	if (isRecording) {
		[mCaptureMovieFileOutput recordToOutputFileURL:nil];
		isRecording = NO ;
	}
}


-(void) setupRecordSession {
	
	
	// Create the capture session.
	mCaptureSession = [[QTCaptureSession alloc] init] ;
	
	// Connect inputs and outputs to the session.
	BOOL success = NO;
    NSError *error;
	
	// Find the device and create the device input. Then add it to the session.
	QTCaptureDevice *videoDevice = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo];
    //if (videoDevice) {
	success = [videoDevice open:&error];
	// If you can’t find or open a video input device, try to find and open a muxed video input device, such as a DV camera
	if (!success) {
		videoDevice = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeMuxed];
		success = [videoDevice open:&error];
	}
	
	// mCaptureDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice:device];
	// success = [mCaptureSession addInput:mCaptureDeviceInput error:&error];
	
	if (!success) {
		// Handle error
		
		videoDevice = nil ;
	}
	
	if (videoDevice) {
		mCaptureVideoDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice:videoDevice];
		success = [mCaptureSession addInput:mCaptureVideoDeviceInput error:&error];
		if (!success) {
			
		}
		
		if (![videoDevice hasMediaType:QTMediaTypeSound] && ![videoDevice hasMediaType:QTMediaTypeMuxed]) {
			
			QTCaptureDevice *audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeSound];
			success = [audioDevice open:&error];
			
			if (!success) {
				audioDevice = nil;
			}
			
			if (audioDevice) {
				mCaptureAudioDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice:audioDevice];
				
				success = [mCaptureSession addInput:mCaptureAudioDeviceInput error:&error];
				if (!success) {
				}
			}
		}
		//}
		
		// Create the movie file output and add it to the session
		mCaptureMovieFileOutput = [[QTCaptureMovieFileOutput alloc] init];
		success = [mCaptureSession addOutput:mCaptureMovieFileOutput error:&error];
		if (!success) {
		}
		[mCaptureMovieFileOutput setDelegate:self];
		
		//Specify the compression options with an identifier with a size for video and a quality for audio
		NSEnumerator *connectionEnumerator = [[mCaptureMovieFileOutput connections] objectEnumerator];
        QTCaptureConnection *connection;
		
        while ((connection = [connectionEnumerator nextObject])) {
            NSString *mediaType = [connection mediaType];
            QTCompressionOptions *compressionOptions = nil;
            if ([mediaType isEqualToString:QTMediaTypeVideo]) {
				// QTCompressionOptionsPrivateH264Video
				//QTCompressionOptionsLosslessAppleIntermediateVideo
                compressionOptions = [QTCompressionOptions compressionOptionsWithIdentifier:@"QTCompressionOptionsLosslessAppleIntermediateVideo"]; // 
            } else if ([mediaType isEqualToString:QTMediaTypeSound]) {
                compressionOptions = [QTCompressionOptions compressionOptionsWithIdentifier:@"QTCompressionOptionsHighQualityAACAudio"];
            }
			
            [mCaptureMovieFileOutput setCompressionOptions:compressionOptions forConnection:connection];
			
			//Associate the capture view in the user interface with the sessio
			[captureView setCaptureSession:mCaptureSession];
		}
		// Start the capture session running
		//[mCaptureSession startRunning];
	}
}

-(void) startSession {
	if(![mCaptureSession isRunning])[mCaptureSession startRunning];
}
-(void) stopSession {
	if([mCaptureSession isRunning])[mCaptureSession stopRunning];
}

- (void)windowWillClose:(NSNotification *)notification
{
    if([mCaptureSession isRunning])[mCaptureSession stopRunning];
    [[mCaptureVideoDeviceInput device] close];
	[[mCaptureAudioDeviceInput device] close];
}

-(void) dealloc {
	[mCaptureSession release];
    [mCaptureVideoDeviceInput release];
	[mCaptureAudioDeviceInput release];
    [mCaptureMovieFileOutput release];
	[captureView release] ;
	[recButton release] ;
	[super dealloc] ;
}


@end
